﻿// See https://aka.ms/new-console-template for more information
using ConsoleApp1;
using Microsoft.Azure.Cosmos;
using System.Configuration;
using System.Net;
using Container = Microsoft.Azure.Cosmos.Container;

class Program
{
    // The Azure Cosmos DB endpoint for running this sample.
    private static readonly string EndpointUri = ConfigurationManager.AppSettings["EndPointUri"];

    // The primary key for the Azure Cosmos account.
    private static readonly string PrimaryKey = ConfigurationManager.AppSettings["PrimaryKey"];

    // The Cosmos client instance
    private static CosmosClient cosmosClient;

    // The database we will create
    private static Database database;

    // The container we will create.
    private static Container container;

    // The name of the database and container we will create
    private static string databaseId = "Cosmos-TaskAssignmentDB";
    private static string containerId = "Task-V2";
    public static async Task Main(string[] args) 
    {
        CosmosClientOptions options = new()
        {
            HttpClientFactory = () => new HttpClient(new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
            }),
            ConnectionMode = ConnectionMode.Gateway
        };
        cosmosClient = new CosmosClient(EndpointUri, PrimaryKey, options);

        database = cosmosClient.GetDatabase(databaseId);
        container = database.GetContainer(containerId);
        //await InitStructure();

        //await InitData();

        var sqlQueryText = "SELECT * FROM c WHERE c.Detail.Claimnumber = 'IA200602'";
        QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);

        FeedIterator<TaskDto> queryResultSetIterator = container.GetItemQueryIterator<TaskDto>(queryDefinition);

        List<TaskDto> taskDtos = new List<TaskDto>();

        while (queryResultSetIterator.HasMoreResults)
        {
            FeedResponse<TaskDto> currentResultSet = await queryResultSetIterator.ReadNextAsync();
            foreach (TaskDto taskDto in currentResultSet)
            {
                taskDtos.Add(taskDto);
                Console.WriteLine("\tRead {0}\n", taskDto);
            }
        }
    }

    /// <summary>
    /// 第一次创建database container
    /// </summary>
    /// <returns></returns>
    private static async Task InitStructure() 
    {
        // Create a new database
        var taDatabaseResponse = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
        var taDatabase = taDatabaseResponse.Database;

        container = await taDatabase.CreateContainerIfNotExistsAsync(containerId, "/partitionKey");
        //await ScaleContainerAsync();
    }

    private static async Task InitData() 
    {
        TaskDto taskDto = new TaskDto
        {
            TaskID = Guid.NewGuid().ToString(),
            TaskLabelID = 58180,
            TaskLabelName = "BA Rating",
            SPAccountID = 908,
            TaskStatusID = 3,
            CaseID = new Random().Next(99999999),
            
            Detail = GetRandomDetail(),
            CreateBy = "walt",
            CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        };

        var re1 = await container.CreateItemAsync<TaskDto>(
           item: taskDto,
           partitionKey: new PartitionKey(taskDto.SPAccountID)
       );
        var re2 = re1.Resource;
    }

    private static dynamic GetRandomDetail()
    {
        List<dynamic> list = new List<dynamic>() 
        {
            new
            {
                AccountName = 1,
                Adjuster = 1,
                Assigned = false,
                ClaimantLetter = false,
                Claimnumber = "IA200601"
            },
            new
            {
                Control_Number = "=",
                Program = "Business Auto"
            },
            new
            {
                AccountName = 2,
                Adjuster = 2,
                Assigned = true,
                ClaimantLetter = false,
                Claimnumber = "IA200602"
            },
            new
            {
                AccountName = 3,
                Adjuster = 3,
                Assigned = false,
                ClaimantLetter = false,
                Claimnumber = "IA200601"
            },
            new
            {
                Claimnumber = "CS198019"
            },
        };
        var index = new Random().Next(list.Count - 1);
        return list[index];
    }

    private static async Task ScaleContainerAsync()
    {
        // Read the current throughput
        try
        {
            int? throughput = await container.ReadThroughputAsync();
            if (throughput.HasValue)
            {
                Console.WriteLine("Current provisioned throughput : {0}\n", throughput.Value);
                int newThroughput = throughput.Value + 100;
                // Update throughput
                await container.ReplaceThroughputAsync(newThroughput);
                Console.WriteLine("New provisioned throughput : {0}\n", newThroughput);
            }
        }
        catch (CosmosException cosmosException) when (cosmosException.StatusCode == HttpStatusCode.BadRequest)
        {
            Console.WriteLine("Cannot read container throuthput.");
            Console.WriteLine(cosmosException.ResponseBody);
        }

    }
}
